import { defineStore } from 'pinia'
import { getBpmReport } from '@/api/bpm/report'

export interface PermissionState {
  bpmCountData: Recordable
  emitFn: null | Function
}

export const useBpmCountStore = defineStore('bpmCount', {
  state: (): PermissionState => ({
    bpmCountData: {},
    emitFn: null
  }),
  getters: {
    getBpmCountData(): any {
      return this.bpmCountData
    }
  },
  actions: {
    // 获取BPM统计数据
    async setBpmCountData(): Promise<void> {
      try {
        const bpmData = await getBpmReport()
        const bpmPathMap = {
          sendCount: 'my',
          todoCount: 'todo',
          doneCount: 'done',
          copyCount: 'copy'
        }
        const data = {}
        Object.keys(bpmData).forEach((key) => {
          const path = bpmPathMap[key]
          if (path) {
            data[path] = bpmData[key]
          }
        })
        this.bpmCountData = data
      } catch (error) {
        this.bpmCountData = {}
      }
    },
    // 设置BPM菜单标题
    setBpmRouteMenuTitle(route: any) {
      let path = route.path
      let countVal = this.bpmCountData[path]
      if (!countVal) {
        if (route.path.includes('/bpm/task/')) {
          path = route.path.replace('/bpm/task/', '')
        } else {
          return route.meta.title
        }
      }
      countVal = this.bpmCountData[path]
      if (!countVal) {
        return route.meta.title
      }
      if (route.meta.title.includes('(')) {
        route.meta.title = `${route.meta.title.split('(')[0]}(${countVal})`
      } else {
        route.meta.title = `${route.meta.title}(${countVal})`
      }
      return route.meta.title
    },
    setEvent(fn: Function) {
      this.emitFn = fn
    },
    emit() {
      this?.emitFn?.()
    }
  },
  persist: false
})
